package com.woniuxy.courseservice.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.core.model.Result;
import com.woniuxy.core.status.OrderState;
import com.woniuxy.core.status.TeamVacateState;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.courseclient.client.OrderFeignClient;
import com.woniuxy.courseclient.client.ProductFeignClient;
import com.woniuxy.courseclient.client.UserFeignClient;
import com.woniuxy.courseclient.client.VenueFeignClient;
import com.woniuxy.courseclient.client.dto.OrderDto;
import com.woniuxy.courseclient.client.dto.TeamProductDto;
import com.woniuxy.courseclient.client.dto.UserInfoDto;
import com.woniuxy.courseclient.client.dto.VenueLoginDto;
import com.woniuxy.coursedao.mapper.TeamCourseMapper;
import com.woniuxy.coursedao.mapper.TeamVacateMapper;
import com.woniuxy.coursedao.model.CourseType;
import com.woniuxy.coursedao.model.TeamCourse;
import com.woniuxy.coursedao.model.TeamVacate;
import com.woniuxy.coursemodel.dto.TeamVacateDto;
import com.woniuxy.coursemodel.param.VacatePageParam;
import com.woniuxy.courseservice.service.TeamVacateService;
import com.woniuxy.courseservice.service.exception.TeamSignInException;
import com.woniuxy.courseservice.service.exception.TeamVacateException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 团课请假记录表 服务实现类
 * </p>
 *
 * @author 冉杰
 * @since 2024-01-15
 */
@Service
public class TeamVacateServiceImpl extends ServiceImpl<TeamVacateMapper, TeamVacate> implements TeamVacateService {

    @Resource
    private TeamCourseMapper teamCourseMapper;
    @Resource
    private UserFeignClient userFeignClient;
    @Resource
    private ProductFeignClient productFeignClient;
    @Resource
    private VenueFeignClient venueFeignClient;

    @Override
    @Transactional
    public void vacate(List<Integer> teamCourseIds, String reason, Integer userId) {
        ArrayList<TeamVacate> list = new ArrayList<>();
        for (Integer teamCourseId : teamCourseIds) {
            TeamCourse teamCourse = teamCourseMapper.selectById(teamCourseId);
            if (ObjectUtil.isEmpty(teamCourse)) throw new TeamVacateException(6020, "部分团课课程不存在");
            Result<TeamProductDto> productDtoResult = productFeignClient.findTeamProductById(teamCourse.getTeamProductId());
            if (!productDtoResult.getFlag())
                throw new TeamVacateException(productDtoResult.getCode(), productDtoResult.getMsg());
            if (BeanUtil.isEmpty(productDtoResult.getData())) throw new TeamVacateException(6010, "部分团课产品不存在");
            TeamProductDto productDto = productDtoResult.getData();
//            Result<OrderDto> orderDtoResult = orderFeignClient.byProductId(productDto.getTeamProductId());
//            if (BeanUtil.isEmpty(orderDtoResult.getData())) throw new TeamVacateException(6008,"该订单不存在");
//            OrderDto orderDto = orderDtoResult.getData();
//            if (orderDto.getOrderState().intValue()!= OrderState.IS_PAID.getState().intValue())
//                throw new TeamVacateException(6011,"该笔订单未支付");
            LocalDateTime now = DateUtil.toLocalDateTime(new Date());
            String endTime = teamCourse.getEndTime();
            DateTime endDateTime = DateUtil.parse(endTime);
            LocalDateTime localDateTime = new Timestamp(endDateTime.getTime()).toLocalDateTime();
            if (now.isAfter(localDateTime)) throw new TeamVacateException(6012, "课程已结束不能请假");
            TeamVacate teamVacate = new TeamVacate();
            teamVacate.setUserId(userId);
            teamVacate.setTeamCourseId(teamCourseId);
            teamVacate.setTeamProductId(productDto.getTeamProductId());
            teamVacate.setVacateTime(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            teamVacate.setVacateReason(reason);
            teamVacate.setVacateState(TeamVacateState.WAIT.getState());
            list.add(teamVacate);
        }
        saveBatch(list);
    }

    @Override
    public PageInfo<TeamVacateDto> byPage(VacatePageParam param) {
        LambdaQueryWrapper<TeamVacate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!ObjectUtil.isEmpty(param.getVenueId()),TeamVacate::getVenueId, param.getVenueId())
                .eq(!ObjectUtil.isEmpty(param.getUserId()),TeamVacate::getUserId, param.getUserId());
        Page<TeamVacate> page = new Page<>(param.getPageNum(), param.getPageSize());
        page(page, wrapper);
        List<TeamVacate> records = page.getRecords();
        ArrayList<TeamVacateDto> list = new ArrayList<>();
        for (TeamVacate record : records) {
            TeamVacateDto teamVacateDto = BeanUtil.toBean(record, TeamVacateDto.class);
            Result<UserInfoDto> userInfoDtoResult = userFeignClient.findUserById(record.getUserId());
            if (!userInfoDtoResult.getFlag()) throw new
                    TeamVacateException(userInfoDtoResult.getCode(), userInfoDtoResult.getMsg());
            UserInfoDto userInfoDto = userInfoDtoResult.getData();
            if (ObjectUtil.isEmpty(userInfoDto)) throw new TeamVacateException(6020, "部分用户不存在");
            teamVacateDto.setUserName(userInfoDto.getUserName());
            Result<VenueLoginDto> venueLoginDtoResult = venueFeignClient.byId(record.getVenueId());
            if (!venueLoginDtoResult.getFlag()) throw new
                    TeamVacateException(venueLoginDtoResult.getCode(), venueLoginDtoResult.getMsg());
            VenueLoginDto venueLoginDto = venueLoginDtoResult.getData();
            if (ObjectUtil.isEmpty(venueLoginDto)) throw new TeamVacateException(6020, "部分场馆不存在");
            teamVacateDto.setVenueName(venueLoginDto.getVenueName());
            Result<TeamProductDto> productDtoResult = productFeignClient.findTeamProductById(record.getTeamProductId());
            if (!productDtoResult.getFlag()) throw new
                    TeamVacateException(productDtoResult.getCode(), productDtoResult.getMsg());
            TeamProductDto teamProductDto = productDtoResult.getData();
            teamVacateDto.setTeamProductName(teamProductDto.getTeamProductName());
            TeamCourse teamCourse = teamCourseMapper.selectById(record.getTeamCourseId());
            teamVacateDto.setStartTime(teamCourse.getStartTime());
            teamVacateDto.setEndTime(teamCourse.getEndTime());
            list.add(teamVacateDto);
        }
        PageInfo<TeamVacateDto> pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    public TeamVacateDto byId(Integer teamVacateId) {
        TeamVacate teamVacate = getById(teamVacateId);
        TeamVacateDto dto = BeanUtil.toBean(teamVacate, TeamVacateDto.class);
        Result<UserInfoDto> userInfoDtoResult = userFeignClient.findUserById(teamVacate.getUserId());
        if (!userInfoDtoResult.getFlag()) throw new
                TeamVacateException(userInfoDtoResult.getCode(), userInfoDtoResult.getMsg());
        UserInfoDto userInfoDto = userInfoDtoResult.getData();
        if (ObjectUtil.isEmpty(userInfoDto)) throw new TeamVacateException(6020, "部分用户不存在");
        dto.setUserName(userInfoDto.getUserName());
        Result<VenueLoginDto> venueLoginDtoResult = venueFeignClient.byId(teamVacate.getVenueId());
        if (!venueLoginDtoResult.getFlag()) throw new
                TeamVacateException(venueLoginDtoResult.getCode(), venueLoginDtoResult.getMsg());
        VenueLoginDto venueLoginDto = venueLoginDtoResult.getData();
        if (ObjectUtil.isEmpty(venueLoginDto)) throw new TeamVacateException(6020, "部分场馆不存在");
        dto.setVenueName(venueLoginDto.getVenueName());
        Result<TeamProductDto> productDtoResult = productFeignClient.findTeamProductById(teamVacate.getTeamProductId());
        if (!productDtoResult.getFlag()) throw new
                TeamVacateException(productDtoResult.getCode(), productDtoResult.getMsg());
        TeamProductDto teamProductDto = productDtoResult.getData();
        dto.setTeamProductName(teamProductDto.getTeamProductName());
        TeamCourse teamCourse = teamCourseMapper.selectById(teamVacate.getTeamCourseId());
        dto.setStartTime(teamCourse.getStartTime());
        dto.setEndTime(teamCourse.getEndTime());
        return dto;
    }

    @Override
    public void agree(Integer teamVacateId, Integer venueId) {
        TeamVacate teamVacate = getById(teamVacateId);
        if (teamVacate.getVenueId().intValue()!=venueId.intValue())
            throw new TeamVacateException(6040,"只能同意自己场馆的请假");
        if (ObjectUtil.isEmpty(teamVacate)) throw new
                TeamVacateException(6031,"该请假信息不存在");
        if (teamVacate.getVacateState().intValue()!=TeamVacateState.WAIT.getState())
            throw new TeamVacateException(6034,"待同意请假才能同意");
        if (teamVacate.getVacateState().intValue()==TeamVacateState.AGREE.getState())
            throw new TeamVacateException(6032,"已同意请假不能重复同意");
        if (teamVacate.getVacateState().intValue()==TeamVacateState.DISAGREE.getState())
            throw new TeamVacateException(6033,"已拒绝请假不能同意");
        teamVacate.setVacateState(TeamVacateState.AGREE.getState());
        updateById(teamVacate);
    }

    @Override
    public void disAgree(Integer teamVacateId, Integer venueId) {
        TeamVacate teamVacate = getById(teamVacateId);
        if (teamVacate.getVenueId().intValue()!=venueId.intValue())
            throw new TeamVacateException(6040,"只能不同意自己场馆的请假");
        if (ObjectUtil.isEmpty(teamVacate)) throw new
                TeamVacateException(6031,"该请假信息不存在");
        if (teamVacate.getVacateState().intValue()!=TeamVacateState.WAIT.getState())
            throw new TeamVacateException(6035,"待同意请假才能不同意");
        if (teamVacate.getVacateState().intValue()==TeamVacateState.DISAGREE.getState())
            throw new TeamVacateException(6036,"不同意请假不能重复不同意");
        if (teamVacate.getVacateState().intValue()==TeamVacateState.AGREE.getState())
            throw new TeamVacateException(6037,"已同意请假不能不同意");
        teamVacate.setVacateState(TeamVacateState.DISAGREE.getState());
        updateById(teamVacate);
    }
}
